import { defineStore } from "pinia";
import { ref } from "vue";
import { useTokenStore } from "../token";
import { API } from "@/services";
import { Role } from "@/services/users/types";
export interface ClassInfo {
  name: string;
  id: number;
}
export const useCourseListStore = defineStore('classList', ()=>{

  const courseList = ref<ClassInfo[]>([]);
  let isInit = false;
  async function dispatchGetClassList() {
    if (isInit) return;
    const tokenStore = useTokenStore();
    await API.courses.getClassList({
      role: tokenStore.token.role,
      id: tokenStore.token.id,
    }).then((res) => {
      if (res.status === 200) {
        if (tokenStore.token.role === Role.Student) {
          courseList.value = res.data.courses.map((item: {name:string, C_id:number}) => {
            return {
              name: item.name,
              id: item.C_id,
            } as ClassInfo;
          });
          isInit = true;
        } else if (tokenStore.token.role === Role.Teacher) {
          courseList.value = res.data.course_list.map((item: {name:string, C_id:number}) => {
            return {
              name: item.name,
              id: item.C_id,
            } as ClassInfo;
          });
          isInit = true;
        }
      }
    }).catch((err) => {
      console.log(err);
    });
  }
  return {
    courseList,
    dispatchGetClassList,
  }
});
